<template>
  <div class="my-orders-page">
    <!-- 顶部功能区 -->
    <div class="header">
      <div class="header-left">
        <img src="@/assets/coffee_logo.png" alt="Logo" class="logo">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="menuItems"
          @click="handleMenuClick"
        />
      </div>
      <div class="header-right">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.userId">
            <a-dropdown>
              <div class="user-info">
                <a-avatar :size="32" :src="loginUserStore.loginUser.avatar">
                  {{ loginUserStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
                </a-avatar>
                <span class="username" :title="loginUserStore.loginUser.userName">{{ loginUserStore.loginUser.userName ?? '未命名'}}</span>
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="profile" @click="showProfileModal">
                    <user-outlined />
                    <span>个人信息</span>
                  </a-menu-item>
                  <a-menu-item key="logout" @click="handleLogout">
                    <logout-outlined />
                    <span>退出</span>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" @click="showLoginModal">登录</a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <a-spin :spinning="loading">
        <a-empty v-if="orders.length === 0" description="暂无订单" />
        <a-card v-for="order in orders" :key="order.orderId" class="order-card">
          <template #title>
            <div class="order-header">
              <span class="order-id">订单号：{{ String(order.orderId) }}</span>
              <div class="order-status">
                <a-tag :color="getStatusColor(order.status)">{{ getStatusText(order.status) }}</a-tag>
                <span v-if="[1, 2, 3].includes(order.status)" class="pick-code">取餐码：{{ order.pickCode }}</span>
              </div>
            </div>
          </template>
          <div class="order-content">
            <div class="order-items">
              <div v-for="item in order.orderItemList" :key="item.productId" class="order-item">
                <img 
                  :src="item.imageUrlList && item.imageUrlList.length > 0 ? item.imageUrlList[0] : ''" 
                  :alt="item.name" 
                  class="item-image"
                >
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-description">{{ item.description }}</div>
                  <div class="item-params" v-if="item.paramList && item.paramList.length > 0">
                    <a-tag v-for="param in item.paramList" :key="param.paramValueId" class="param-tag">
                      {{ param.paramValueName }}
                    </a-tag>
                  </div>
                  <div class="item-price">¥{{ item.price }} × {{ item.quantity }}</div>
                </div>
              </div>
            </div>
            <div class="order-footer">
              <div class="order-total">
                总计：<span class="total-amount">¥{{ order.totalPrice }}</span>
              </div>
              <div class="order-actions">
                <a-button v-if="order.status === 0" type="primary" @click="handlePay(order)">
                  立即支付
                </a-button>
                <a-button v-if="order.status === 3" type="primary" @click="handlePick(order)">
                  取餐
                </a-button>
              </div>
            </div>
          </div>
        </a-card>

        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <a-pagination
            v-model:current="pagination.current"
            v-model:pageSize="pagination.pageSize"
            :total="pagination.total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :show-total="(total: number) => `共 ${total} 条`"
            @change="handlePageChange"
            @showSizeChange="handlePageChange"
          />
        </div>
      </a-spin>
    </div>

    <!-- 登录弹窗 -->
    <LoginModal ref="loginModalRef" />

    <!-- 个人信息弹窗 -->
    <a-modal
      v-model:visible="profileModalVisible"
      title="个人信息"
      @ok="hideProfileModal"
      @cancel="hideProfileModal"
      :footer="null"
    >
      <div class="profile-container">
        <div class="profile-avatar">
          <template v-if="!isEditing">
            <a-avatar :size="64" :src="loginUserStore.loginUser.avatar">
              {{ loginUserStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
            </a-avatar>
          </template>
          <template v-else>
            <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
              :max-count="1"
              :customRequest="customRequest"
            >
              <div v-if="imageUrl" class="avatar-preview">
                <img :src="imageUrl" alt="avatar" />
              </div>
              <div v-else class="avatar-placeholder">
                <plus-outlined />
                <div style="margin-top: 8px">上传头像</div>
              </div>
            </a-upload>
          </template>
        </div>
        <div class="profile-info">
          <div class="profile-item">
            <span class="profile-label">用户名：</span>
            <template v-if="!isEditing">
              <span class="profile-value">{{ loginUserStore.loginUser.userName }}</span>
            </template>
            <template v-else>
              <a-input v-model:value="formState.userName" placeholder="请输入用户名" />
            </template>
          </div>
          <div class="profile-item">
            <span class="profile-label">用户ID：</span>
            <span class="profile-value">{{ loginUserStore.loginUser.userId }}</span>
          </div>
          <div class="profile-item">
            <span class="profile-label">手机号：</span>
            <span class="profile-value">{{ loginUserStore.loginUser.phone }}</span>
          </div>
        </div>
        <div class="profile-actions">
          <template v-if="!isEditing">
            <a-button type="primary" @click="handleEditProfile">
              <edit-outlined /> 编辑
            </a-button>
          </template>
          <template v-else>
            <a-button type="primary" @click="handleSaveProfile" style="margin-right: 8px;">
              <check-outlined /> 保存
            </a-button>
            <a-button @click="isEditing = false">
              <close-outlined /> 取消
            </a-button>
          </template>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  UserOutlined,
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  LogoutOutlined,
  HomeOutlined,
  FileTextOutlined,
  ShopOutlined,
  PlusOutlined
} from '@ant-design/icons-vue';
import { MenuProps, message } from 'ant-design-vue';
import { useLoginStore } from "@/store/useLoginUserStore";
import { editUser, getCurrentUser } from "@/api/user";
import { uploadFile } from "@/api/file";
import LoginModal from '@/components/LoginModal.vue';
import { listOrder, pay, pick } from "@/api/order";
import type { UploadProps } from 'ant-design-vue';

const router = useRouter();
const loginUserStore = useLoginStore();
const loginModalRef = ref();
const profileModalVisible = ref(false);
const isEditing = ref(false);
const formState = reactive({
  userName: ''
});

// 头像上传相关
const fileList = ref<any[]>([]);
const imageUrl = ref('');

// 导航菜单相关
const current = ref<string[]>([]);
const menuItems = ref<MenuProps['items']>([
  {
    key: '/order',
    icon: () => h(HomeOutlined),
    label: '首页',
    title: '首页',
  },
  {
    key: '/my-orders',
    icon: () => h(FileTextOutlined),
    label: '我的订单',
    title: '我的订单',
  }
]);

// 根据当前路由设置选中的菜单项
const setCurrentMenu = () => {
  const path = router.currentRoute.value.path;
  current.value = [path];
};

// 监听路由变化
watch(() => router.currentRoute.value.path, () => {
  setCurrentMenu();
});

// 检查并恢复登录状态
const checkLoginStatus = async () => {
  const token = localStorage.getItem('token');
  if (token && !loginUserStore.loginUser.userId) {
    try {
      const res = await getCurrentUser();
      if (res.data.code === 200) {
        loginUserStore.loginUser = res.data.data;
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  }
};

// 初始化时设置当前菜单
onMounted(async () => {
  setCurrentMenu();
  try {
    await checkLoginStatus();
    await fetchOrders();
  } catch (error) {
    console.error('初始化失败:', error);
    loading.value = false;
  }
});

// 订单列表数据
const orders = ref<any[]>([]);
const loading = ref(false);

// 分页参数
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 获取订单列表
const fetchOrders = async () => {
  if (!loginUserStore.loginUser.userId) {
    orders.value = [];
    pagination.value.total = 0;
    loading.value = false;  // 确保在未登录时重置 loading 状态
    return;
  }

  try {
    loading.value = true;
    const today = new Date();
    const startTime = today.toISOString().split('T')[0] + ' 00:00:00';
    const endTime = today.toISOString().split('T')[0] + ' 23:59:59';

    const res = await listOrder({
      storeId: '',  // 用户订单不需要storeId
      status: -1,   // 获取所有状态
      startTime,
      endTime,
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    });
    if (res.data.code === 200) {
      orders.value = res.data.data.list.map((order: any) => ({
        ...order,
        orderId: String(order.orderId)
      }));
      pagination.value.total = res.data.data.total;
      pagination.value.pageSize = res.data.data.pageSize;
      pagination.value.current = res.data.data.pageNum;
    } else {
      message.error(res.data.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'processing',
    1: 'success',
    2: 'error'
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待支付',
    1: '已支付',
    2: '制作中',
    3: '待取餐',
    4: '已取消',
    10: '已完成'
  };
  return textMap[status] || '未知状态';
};

// 处理菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  router.push(key);
};

// 显示登录弹窗
const showLoginModal = () => {
  loginModalRef.value.show();
};

// 显示个人信息弹窗
const showProfileModal = () => {
  profileModalVisible.value = true;
  isEditing.value = false;
  formState.userName = loginUserStore.loginUser.userName || '';
  imageUrl.value = loginUserStore.loginUser.avatar || '';
};

// 关闭个人信息弹窗
const hideProfileModal = () => {
  profileModalVisible.value = false;
  isEditing.value = false;
};

// 处理编辑个人信息
const handleEditProfile = () => {
  isEditing.value = true;
};

// 处理保存个人信息
const handleSaveProfile = async () => {
  try {
    const res = await editUser({
      userName: formState.userName,
      avatar: imageUrl.value || loginUserStore.loginUser.avatar
    });

    if (res.data.code === 200) {
      loginUserStore.loginUser.userName = formState.userName;
      if (imageUrl.value) {
        loginUserStore.loginUser.avatar = imageUrl.value;
      }
      message.success('保存成功');
      isEditing.value = false;
      imageUrl.value = '';
      fileList.value = [];
    } else {
      message.error(res.data.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存个人信息失败:', error);
    message.error('保存失败，请稍后重试');
  }
};

// 头像上传相关方法
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片！');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
  }
  return isJpgOrPng && isLt2M;
};

const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      imageUrl.value = res.data.data.url;
      message.success('头像上传成功');
    } else {
      onError(new Error(res.data.msg || '头像上传失败'));
    }
  } catch (error) {
    console.error('头像上传失败:', error);
    onError(error);
    message.error('头像上传失败，请稍后重试');
  }
};

const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
  fileList.value = newFileList;
};

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('token');
  loginUserStore.loginUser = {};
  router.push('/user/login');
};

// 处理支付
const handlePay = async (order: any) => {
  try {
    const res = await pay(order.orderId);
    if (res.data.code === 200) {
      message.success('支付成功');
      // 刷新订单列表
      fetchOrders();
    } else {
      message.error(res.data.msg || '支付失败');
    }
  } catch (error) {
    console.error('支付失败:', error);
    message.error('支付失败，请稍后重试');
  }
};

// 处理再次下单
const handleReorder = (order: any) => {
  // TODO: 实现再次下单逻辑
  router.push('/order');
};

// 处理取餐
const handlePick = async (order: any) => {
  try {
    const res = await pick(order.orderId, order.pickCode);
    if (res.data.code === 200) {
      message.success('取餐成功');
      // 刷新订单列表
      fetchOrders();
    } else {
      message.error(res.data.msg || '取餐失败');
    }
  } catch (error) {
    console.error('取餐失败:', error);
    message.error('取餐失败，请稍后重试');
  }
};

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
  fetchOrders();
};
</script>

<style scoped>
.my-orders-page {
  min-height: 100vh;
  background: #F5F5F5;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: white;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left :deep(.ant-menu) {
  background: transparent;
  border-bottom: none;
}

.header-left :deep(.ant-menu-item) {
  color: #666;
}

.header-left :deep(.ant-menu-item-selected) {
  color: #1890ff;
}

.header-left :deep(.ant-menu-item:hover) {
  color: #1890ff;
}

.header-left :deep(.ant-menu-item::after) {
  display: none;
}

.header-left :deep(.ant-menu-item-selected::after) {
  display: block;
  border-bottom: 2px solid #1890ff;
}

.logo {
  height: 40px;
}

.order-list {
  margin-top: 80px;
  padding: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.order-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-id {
  color: #666;
  font-size: 14px;
}

.order-content {
  padding: 16px 0;
}

.order-items {
  margin-bottom: 16px;
}

.order-item {
  display: flex;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.item-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-params {
  margin: 8px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.param-tag {
  margin: 0;
  border-radius: 4px;
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  color: #666;
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

.param-tag:hover {
  background: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
}

.item-price {
  color: #1890ff;
  font-weight: 500;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.order-total {
  font-size: 16px;
  color: #666;
}

.total-amount {
  color: #1890ff;
  font-weight: bold;
  font-size: 18px;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.user-login-status {
  margin-left: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.username {
  font-size: 14px;
  color: #333;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.profile-avatar {
  margin-bottom: 20px;
}

.profile-info {
  width: 100%;
}

.profile-item {
  margin-bottom: 12px;
  display: flex;
}

.profile-label {
  font-weight: bold;
  width: 80px;
  color: #666;
}

.profile-value {
  color: #333;
}

.profile-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pick-code {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 500;
}

.avatar-uploader {
  width: 128px;
  height: 128px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}
</style>
